
var google_client_id = '559435268503.apps.googleusercontent.com';
var redirect_uri = 'http%3A%2F%2Flocalhost%2Foauth2callback';


$(document).ready(function(){
   

    //**************************//
    //**  ACTIVITY SELECTION  **//


    // Need to abstract the Activity Selection
    // so here's a constructor for an ActivitySelection object:
    function ActivitySelection(title, blockColor, HLColor, fontHL){
	this.title = title;
	this.blockColor = blockColor;
	this.HLColor = HLColor;
	this.fontHL = fontHL;
	this.selected = false;

	this.element = $('#'+title);
    }

    var activityHash = {}
    activityHash['eating'] = new ActivitySelection('eating', 'red', '#FF0000', '#000000');
    activityHash['spiritual'] = new ActivitySelection('spiritual', 'orange', '#FF6600', '#000000');
    activityHash['class'] = new ActivitySelection('class',  'yellow', '#FFFF00', '#000000');
    activityHash['studying'] = new ActivitySelection('studying', 'green', '#006600', '#FFFFFF');
    activityHash['work'] = new ActivitySelection('work',  'lime', '#00FF00', '#000000');
    activityHash['exercising'] = new ActivitySelection('exercising', 'blue', '#0000FF', '#FFFFFF');
    activityHash['socializing'] = new ActivitySelection('socializing', 'white', '#FFFFFF', '#000000');
    activityHash['sleeping'] = new ActivitySelection('sleeping', 'black', '#000000', '#FFFFFF');
    activityHash['drinking'] = new ActivitySelection('drinking', 'brown', '#8B4513', '#FFFFFF');
    activityHash['miscellaneous'] = new ActivitySelection('miscellaneous', 'gray', '#757575', '#FFFFFF');
    
    
    // Initially highlight "eating"
    $("#eating").css({'background-color':'#FF0000'});
    activityHash['eating'].selected=true;

    // When user selects an activity, reset all backgrounds to 'inherit' and all "selected" fields to false
    // change the selected element's block images and colors to indicate to the user that it was selected
    $("span.activity").click(function(event) {
	event.stopPropagation();
	var activity = $(this).attr('id');

	var key;
	for (key in activityHash) {
		activityHash[key].selected = false;
		activityHash[key].element.css({'background-color':'inherit', 'color':activityHash[key].HLColor});
	}

	$("#blocks .block_15, #blocks .block_30, #blocks .block_60")
	    .css("background-image","url(/static/images/block_"+activityHash[activity].blockColor+".jpg)")
	    .attr('title',activity);
	$(this).css({'background-color': activityHash[activity].HLColor, 'color': activityHash[activity].fontHL});
	activityHash[activity].selected = true;
    });


    // When user HOVERS over an Activity, change background color to the activity color... 
    // when cursor leaves, change to 'inherit' iff it's not selected
    $('span.activity').hover(
	function(){
	    var activity = $(this).attr('id');
	    $(this).css({'background-color':activityHash[activity].HLColor, 'color': activityHash[activity].fontHL});
	},
	function(){
	    var activity = $(this).attr('id');
	    if (activityHash[activity].selected == false)
		$(this).css({'background-color': 'inherit', 'color': activityHash[activity].HLColor});
	});


    //*********************//
    //**  DRAG AND DROP  **//

    var downSound = "/static/sounds/down.mp3";
    var upSound   = "/static/sounds/up.mp3";
    var currentlyDragging;

    function initSound (filePath) {
	    $("#sound").html('').jmp3({		
		"filepath": filePath,
		"repeat": "no",	
		"volume": "100",
		"autoplay": "true",
	    });	
    }

    // Return false if the newBlock added to the current contents of 'cell' 
    // will put that cell's total time over an hour or true otherwise
    function isLessThanHour(newBlock, cell) {
	var len = 0;
	if (newBlock.hasClass("block_15")) len = 15;
	else if (newBlock.hasClass("block_30")) len = 30;
	else len = 60;

	cell.find("*").each(function(){
	    var block = $(this);
	    if (block.hasClass("block_15")) len += 15;
	    else if (block.hasClass("block_30")) len += 30;
	    else len += 60;
	});

	return len <= 60;
    }



    // initialize timeblock
    $(".block").draggable({
	helper:		"clone",
	start: function(event, ui) {
	    $('.instructions').hide();
	    currentlyDragging = $(this);
	    // since these are menu elements, we add a class that makes them distinct from the blocks on the board
	    ui.helper.addClass('menu-block');
	    initSound(upSound);
	}
    });


    // make a droppable location and allow for re-dragging of set down blocks
    $(".cal-cell").droppable({
	accept:	   ".block",
	tolerance: "intersect",
	greedy:true,
	drop: function(event, ui){
	    var dropCell = $(this);

	    initSound(downSound);

	    // If we're dragging a menu block, then clone it (we need it to stay in the menu)... otherwise just keep the actual block
	    var myBlock = (ui.helper.hasClass('menu-block')) ? ui.draggable.clone() : ui.draggable;
	    currentlyDragging.show();

	    if (isLessThanHour(myBlock, dropCell)) {
	  	myBlock 
		    .appendTo(dropCell) // append the block to the new cell
		    .draggable( {       // make it draggable again
			helper:   "clone",
			start: function(event, ui) {
			    myBlock.hide();
			    currentlyDragging = $(this);
			    initSound(upSound);
			},
			stop: function(event,ui) {
			    currentlyDragging.show();
			}
		    })
		    .css({ // reapply the original block's CSS settings (they aren't copied over)
			"background-image": ui.helper.css("background-image"),
			"width":    ui.helper.css("width"),
			"height":   ui.helper.css("height"),
			"position": "relative",
			"top":      "0px",
			"left":     "0px",
			"display":  "block",
			"float":    "left"
		    });
	    }
	}
    }); 


    $('#trashcan').droppable({
	accept: '.block',
	tolerance: 'touch',
	drop: function (event, ui) {
	    if (!ui.helper.hasClass('menu-block')) ui.draggable.remove();
	}
    });


    //********************//
    //**  COPY | PASTE  **//

    var daysOfWeek = new Array("sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday");
    var hoverDay = "";  // day we're hovering over
    var day2copy = "";  // day we've selected for copy
   
    // hovering over the headers reveals the Copy | Paste options
    $('th.title-cell').hover(
	function () {
	    hoverDay = $(this).attr('title');
	    if (hoverDay != day2copy) $(this).css({'background-color':'#FFCC00', 'color':'#000000'});
	    $(this).html('<span class="copy">copy</span> &nbsp|&nbsp <span class="paste">paste</span>');
	    
	    /** Clicking "copy" sets up a day to be copied (internally and also visually) **/
	    $('span.copy').click(function () {
		day2copy = hoverDay;
		var i;
		for (i in daysOfWeek)
		    $('th.'+daysOfWeek[i]).css({'background-color':'#EEEEEE', 'color':'#000000'});
		$(this).parent().css({'background-color':'#00FF00', 'color':'#000000'});
	    });
	    
	    // I sure wish I knew what Backbone.js was before I started this project...
	    /** Clicking paste copies everything from day2copy over to hoverDay using .clone() and .appendTo **/
	    $('span.paste').click(function () {
		if (day2copy != hoverDay && day2copy != "") {

		    //clear every slot in the day we're hovering over
		    $('td.'+hoverDay.toLowerCase()).each(function(i,el){$(el).html('')});

		    function copyOver(time, edge) {
			$('tr.time_'+time+' td.'+edge+'.'+day2copy.toLowerCase()+' div.block')
			    .clone(false).each(function(index, element) {
				var clone = $(element);
				clone.appendTo('tr.time_'+time+' td.'+edge+'.'+hoverDay.toLowerCase());
				clone.draggable( {       // make it draggable again
				    helper:   "clone",
				    snap:     ".cal-cell, .block",
				    snapMode: "outer",
				    start: function(event, ui) {
					clone.hide();
					currentlyDragging = $(this);
					initSound(upSound);
				    },
				    stop: function(event,ui) {
					currentlyDragging.show();
				    }
				}).css({
				    "background-image": clone.css("background-image"),
				    "width":    clone.css("width"),
				    "height":   clone.css("height"),
				    "position": "relative",
				    "top":      "0px",
				    "left":     "0px",
				    "display":  "block",
				    "float":    "left"
				});
				
			    });
			}
		    }

		    var i;
		    for (i = 1; i <= 24; i++) {
			copyOver(i, "left-edge");
			copyOver(i, "middle-cell");
			copyOver(i, "right-edge");
		    }
		});
	},
	function () {
	    $(this).html(hoverDay);
	    if (hoverDay != day2copy)
		$(this).css({'background-color':'#EEEEEE', 'color':'#000000'});
	}
    );


    // Hide Instructions upon clicking anywhere
    $(document).bind('click', function (e) {
	$('.instructions').hide();
    });
    

});



//*********************//
//**  DATA HANDLING  **//


//Constructor for all TimeBlockTrasport objects
function TimeBlockTransport() {
    this.timeblocks=new Array();
};


//Constructor for all TimeBlock objects (matches the structure of the server-side TimeBlocks)
function TimeBlock(duration, activity, alignment, hour, day) {
    this.duration = duration;   // (15, 30, 60 min)
    this.activity = activity;   // (1 - 8)
    this.alignment = alignment; // (1 - 3)
    this.hour = hour;           // (1 - 24)
    this.day = day;             // (0 - 6)
};

function makeBlockArray() {    
    var transport = new TimeBlockTransport();
    
    // loop through all the cells on the table
    $("td.cal-cell").each(function(){
	var temp = $(this);


	// get cell column
	var day = 0;
	if (temp.hasClass("col_0")) day = 0;
	else if (temp.hasClass("col_1")) day = 1;
	else if (temp.hasClass("col_2")) day = 2;
	else if (temp.hasClass("col_3")) day = 3;
	else if (temp.hasClass("col_4")) day = 4;
	else if (temp.hasClass("col_5")) day = 5;
	else if (temp.hasClass("col_6")) day = 6;

	// get cell alignment
	var alignment = 2;
	if (temp.hasClass("left-edge")) alignment = 0;
	else if (temp.hasClass("middle-cell")) alignment = 1;
	
	// get cell hour
	var hour = 0;
	hour = parseInt (
	    temp.parent().attr('class').replace('time_', '')
	) - 1;

	// iterate over blocks in the cell
	$(this).children().each( function(){
	    var duration = 0;
	    var activity = "";

	    // set block duration
	    temp = $(this);
	    if(temp.hasClass("block_15")) duration = 15;
	    else if(temp.hasClass("block_30")) duration = 30;
	    else if(temp.hasClass("block_60")) duration = 60;

	    // set block activity
	    activity = temp.attr('title');

	    transport.timeblocks.push(new TimeBlock(duration, activity, alignment, hour, day));
	});
    });

    
    return transport;
}


// Put everything into a multi-dimensional array and submit from client side (type, category, alignment, row, column) to server side
function analyze_calendar (isReal) {
    window.scrollTo(0,0); //move position to top of screen so user can see intro

    var transport = makeBlockArray();

    if (isReal == 'yes') 
	$('#save').attr('onclick','analyze_calendar("no");');
	
    // use AJAX to upload the transport-array of timeblocks to the server for parsing and insertion into database
    $.ajax({
	type:           'post',
	contentType:    'application/json; charset=utf-8',
	cache:          false,
	url:            '/analyze_calendar?isReal='+isReal,
	data:           JSON.stringify(transport),
	success: function(data) {
	    var json_data = JSON.parse(JSON.stringify(data));
	    var analysis = json_data.analysis;
	    var cid = json_data.cid;

	    $('#analysis').html(analysis);
	    $("#phase2_intro").dialog({ 
		minWidth : 1000,
		title    : "Analysis Feedback:",
		resizable: false,
		modal    : true,
		draggable: false,
		buttons  : { "Ok": function() { $(this).dialog("close"); } }});

	    $('#google').show();

	    /** SETUP EXPORT TO GOOGLE CALENDAR **/
	    $('#google').click(function () {
		// use AJAX to upload the transport-array of timeblocks to the server for parsing and then export to Google Calendar
		$.ajax({
		    type:           'post',
		    contentType:    'application/json; charset=utf-8',
		    cache:          false,
		    url:            '/export_calendar',
		    data:           JSON.stringify(makeBlockArray()),
		    success: function (tempFile) {
			window.open('https://accounts.google.com/o/oauth2/auth?'+
				    'scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar&'+
				    'redirect_uri='+redirect_uri+'&'+
				    'response_type=token&'+
				    'state='+tempFile+'&'+
				    'client_id='+google_client_id);
		    }
		});
	    });


	    /** SETUP EXCEL DOWNLOAD **/
	    $('#excel').show();
	    $('#excel').click(function () {
		$('#excel_data').attr('value', JSON.stringify(makeBlockArray()));
		$('#excel_filename').attr('value', cid+'.xls');
		$('#excel_form').submit();
	    });
	}
    });
}